/**
 * Created by Administrator on 2017/7/21 0021.
 */
define(function(){
    var obj = {};
    obj.add = function(box,div){
        obj.box = document.querySelector(box);
        obj.div = document.querySelector(div);
        obj.ajax();
    };
    obj.ajax = function(){
        var xhr = new XMLHttpRequest();
        xhr.open("get","http://localhost:8888/lunbo",true);
        xhr.send();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status>=200 && xhr.status<=300 || xhr.status == 304){
                    obj.createHandler(JSON.parse(xhr.responseText))
                }
            }
        }
    };
    obj.createHandler = function(o){
        obj.x = obj.box.offsetWidth;
        obj.len = o.img.length;
        obj.num = obj.len-1;
        obj.div.style.width = o.img.length*obj.x+"px";
        var y = obj.div.offsetHeight;
        obj.p = obj.box.querySelector("p");
        for(var i = 0;i< o.img.length;i++){
            var img = new Image();
            img.src = o.img[i];
            obj.div.appendChild(img);
            img.style.width = obj.x+"px";
            img.style.height = y+"px";
            var is = document.createElement("i");
            obj.p.appendChild(is);
            is.style.right = 50+10*i+15*i+"px";
        }
        obj.arr = obj.p.querySelectorAll("i");
        obj.lun();
    };
    obj.lun = function(){
        var imgs = obj.div.firstElementChild;
        for(var i = 0;i<obj.len;i++){
            (function(m){
                obj.arr[m].onclick = function(){
                    console.log(m,this);
                }
            })(i);
            if(i == obj.num){
                obj.arr[i].style.backgroundColor = "gray";
            }else {
                obj.arr[i].style.backgroundColor = "white";
            }
        }

        obj.div.appendChild(imgs);
        obj.div.style.left = 0;
        var s = 0;
        var id = setInterval(lun,10);
        function lun(){
            s++;
            if(s >= 200){
                obj.div.style.left = obj.div.offsetLeft-2+"px";
            }
            if(obj.div.offsetLeft == -obj.x){
                obj.num--;
                if(obj.num == -1){
                    obj.num = obj.len-1
                }
                obj.lun();
                clearInterval(id);
            }
        }
    };
    return obj
});